import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
app.use(express.json());


// 使用动态端口配置
const WS_PORT = process.env.WS_PORT || 8081;
const HTTP_PORT = process.env.PORT || 3001;
// 创建WebSocket服务器
const wss = new WebSocketServer({ port: WS_PORT });

// 连接池管理
const clients = new Set();

wss.on('connection', (ws) => {
  clients.add(ws);
  console.log('新客户端连接，当前连接数:', clients.size);

  // 心跳检测
  let heartbeatInterval = setInterval(() => {
    if (ws.readyState === ws.OPEN) {
      ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));
    }
  }, 30000);

  // 消息处理
  ws.on('message', (data) => {
    const message = data.toString();
    try {
      const msgObj = JSON.parse(message);
      
      // 处理心跳响应
      if (msgObj.type === 'pong') {
        console.log('收到心跳响应:', msgObj);
        return;
      }

      // 广播消息给所有客户端
      clients.forEach(client => {
        if (client !== ws && client.readyState === client.OPEN) {
          client.send(JSON.stringify({
            type: 'broadcast',
            payload: msgObj,
            from: 'server'
          }));
        }
      });
    } catch (e) {
      console.error('消息解析错误:', e);
    }
  });

  // 连接关闭处理
  ws.on('close', () => {
    clients.delete(ws);
    clearInterval(heartbeatInterval);
    console.log('客户端断开，剩余连接数:', clients.size);
  });

  // 发送欢迎消息
  ws.send(JSON.stringify({
    type: 'system',
    message: '连接已建立',
    timestamp: Date.now()
  }));
});

// 测试用HTTP端点
app.get('/broadcast', (req, res) => {
  const message = req.query.msg || '服务器广播消息';
  clients.forEach(client => {
    if (client.readyState === client.OPEN) {
      client.send(JSON.stringify({
        type: 'broadcast',
        payload: message,
        from: 'server'
      }));
    }
  });
  res.send('消息已广播');
});

app.listen(HTTP_PORT, () => {
  console.log(`HTTP服务器运行在 http://localhost:${HTTP_PORT}`);
  console.log(`WebSocket服务器运行在 ws://localhost:${WS_PORT}`);
});